/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.qxp.simplerpc.server;

import com.qxp.simplerpc.annotation.Service;
import com.qxp.simplerpc.entity.InvokerMessage;
import com.qxp.simplerpc.exception.RpcException;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Handles both com.qxp.example-side and com.qxp.example-side handler depending on which
 * constructor was called.
 */

/**
 * @author qianxiaopeng
 */
@SuppressWarnings("unchecked")
@Component
@ChannelHandler.Sharable
public class RpcServerHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(RpcServerHandler.class);
    // 通道内容句柄
    private ChannelHandlerContext ctx;

    @Autowired
    private RpcServerInvoker invoker;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        setCtx(ctx);
        invoke(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("rpc com.qxp.example exception,caused by:\n", cause);
        ctx.close();
    }

    public void closeChannelContext() {
        getCtx().close();
    }

    public ChannelHandlerContext getCtx() {
        return ctx;
    }

    public void setCtx(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    private void invoke(ChannelHandlerContext ctx, Object msg) {
        InvokerMessage invokerMessage = (InvokerMessage) msg;
        try {
            ctx.writeAndFlush(invoker.invoke(invokerMessage));
        }catch (Exception cln){
            logger.error("rpc com.qxp.example channel read error,method invoking error,caused by:\n", cln);
        }
    }

}
